package com.onec.service.route.service.impl;

import com.onec.service.api.enums.ProductEnum;
import com.onec.service.api.enums.StatusEnum;
import com.onec.service.api.enums.SystemTypeEnum;
import com.onec.service.api.enums.error.RouteErrorEnum;
import com.onec.service.api.exception.RouteException;
import com.onec.service.route.dao.TradeConfigRepository;
import com.onec.service.route.entity.TradeConfigInfo;
import com.onec.service.route.service.TradeConfigInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author onec
 * @see
 */
@Service
public class TradeConfigServiceImpl implements TradeConfigInfoService {


    @Autowired
    TradeConfigRepository tradeConfigRepository;

    /**
     * 交易状态：提现状态：产品状态：
     *
     * @param product
     * @param type
     * @return
     */
    @Override
    public List<TradeConfigInfo> getAvailableTradeConfig(ProductEnum product, SystemTypeEnum type) {
        List<TradeConfigInfo> tradeConfigInfos = tradeConfigRepository.findByTypeAndProduct(type, product);
        if (Optional.ofNullable(tradeConfigInfos).isPresent()) {
            tradeConfigInfos = tradeConfigInfos
                    .stream()
                    .filter(e -> StatusEnum.isSuccess(e.getStatus()))
                    .collect(Collectors.toList());
        }
        if (tradeConfigInfos == null || tradeConfigInfos.size() == 0) {
            throw new RouteException(RouteErrorEnum.MERCHANT_TRADE_RULE_DOING, product.name());
        }
        return tradeConfigInfos;
    }

    @Override
    public TradeConfigInfo findByBusinessNoType(String businessNo, SystemTypeEnum systemTypeEnum) {
        TradeConfigInfo tradeConfigInfo =
                tradeConfigRepository.findByBusinessNoAndType(businessNo, systemTypeEnum);

        if (Optional.ofNullable(tradeConfigInfo).isEmpty() || !StatusEnum.isSuccess(tradeConfigInfo.getStatus())) {
            throw new RouteException(RouteErrorEnum.MERCHANT_TRADE_RULE_DOING, businessNo);
        }
        return tradeConfigInfo;
    }


}
